import 'package:flutter/material.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tdesign_flutter/src/theme/td_theme.dart';
import 'package:flutter_wisave/Common/TimeSwitching.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../Tools/ToolsLocalStorage.dart';

class DeviceStop02 extends StatefulWidget {
  final double height;

  const DeviceStop02({super.key, required this.height});

  @override
  State<DeviceStop02> createState() => _DeviceStop02State();
}

class _DeviceStop02State extends State<DeviceStop02>
    with SingleTickerProviderStateMixin {
  DateTime _currentDayDateTime = DateTime.now();
  late String currentDayDate = _formatDate(DateTime.now());
  final NetworkService _networkService = NetworkService();
  List<dynamic> dataList = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          dataList = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/tappingtimeday/steelTappingTimeWeek?companyId=$deptID&date=$currentDayDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('deptList Failed to load data');
      }
    } catch (e) {
      print('deptList Error in _fetchData: $e');
      rethrow;
    }
  }

  void _onDayDateChanged(DateTime newDate) {
    setState(() {
      _currentDayDateTime = newDate;
      currentDayDate = _formatDate(_currentDayDateTime);
      _loadData();
    });
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString()}';
  }

  String _showTime(String startTime, String endTime) {
    DateTime start = DateTime.parse(startTime);
    DateTime end = DateTime.parse(endTime);
    return '${start.month.toString().padLeft(2, '0')}.${start.day.toString().padLeft(2, '0')}/${end.month.toString().padLeft(2, '0')}.${end.day.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16),
      child: Container(
        width: double.infinity,
        // height: 100,
        padding: EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: AppColors.cardColor,
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.2),
              blurRadius: 6.0,
            ),
          ],
        ),
        child: Column(children: [
          TimeSwitching(
            mode: SwitchingMode.month,
            onDateChanged: _onDayDateChanged,
          ),
          const SizedBox(height: 10),
          Container(
            height: 1,
            width: double.infinity,
            color: AppColors.dividerColor,
          ),
          const SizedBox(height: 10),
          if (dataList.length > 0)
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Image(
                            image: AssetImage(
                                'assets/images/centre/toppieBg1.png'),
                            width: 70,
                            height: 70,
                          ),
                          Positioned(
                            child: Text(
                              dataList[0]['ratio'].toString() + '%',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF2AB6F7),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                              _showTime(
                                  dataList[0]['start'], dataList[0]['end']),
                              style: TextStyle(
                                  fontSize: 10,
                                  color: AppColors.textSecondary)),
                          Text("作业时间${dataList[0]['tappingTime'].toString()}h",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: AppColors.textSecondary)),
                          Text("停机时间${dataList[0]['stopTime'].toString()}h",
                              style: TextStyle(
                                  fontSize: 12, color: AppColors.textSecondary))
                        ],
                      )
                    ],
                  ),
                ),
                if (dataList.length > 1)
                  Expanded(
                    child: Row(
                      children: [
                        Stack(
                          alignment: Alignment.center,
                          children: [
                            Image(
                              image: AssetImage(
                                  'assets/images/centre/toppieBg1.png'),
                              width: 70,
                              height: 70,
                            ),
                            Positioned(
                              child: Text(
                                dataList[1]['ratio'].toString() + '%',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFF2AB6F7),
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 10),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                                _showTime(
                                    dataList[1]['start'], dataList[1]['end']),
                                style: TextStyle(
                                    fontSize: 10,
                                    color: AppColors.textSecondary)),
                            Text(
                                "作业时间${dataList[1]['tappingTime'].toString()}h",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.textSecondary)),
                            Text("停机时间${dataList[1]['stopTime'].toString()}h",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.textSecondary))
                          ],
                        )
                      ],
                    ),
                  ),
              ],
            ),
          const SizedBox(height: 10),
          Container(
            height: 1,
            width: double.infinity,
            color: AppColors.dividerColor,
          ),
          const SizedBox(height: 10),
          if (dataList.length > 2)
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Image(
                            image: AssetImage(
                                'assets/images/centre/toppieBg1.png'),
                            width: 70,
                            height: 70,
                          ),
                          Positioned(
                            child: Text(
                              dataList[2]['ratio'].toString() + '%',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF2AB6F7),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                              _showTime(
                                  dataList[2]['start'], dataList[2]['end']),
                              style: TextStyle(
                                  fontSize: 10,
                                  color: AppColors.textSecondary)),
                          Text("作业时间${dataList[2]['tappingTime'].toString()}h",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: AppColors.textSecondary)),
                          Text("停机时间${dataList[2]['stopTime'].toString()}h",
                              style: TextStyle(
                                  fontSize: 12, color: AppColors.textSecondary))
                        ],
                      )
                    ],
                  ),
                ),
                if (dataList.length > 3)
                  Expanded(
                    child: Row(
                      children: [
                        Stack(
                          alignment: Alignment.center,
                          children: [
                            Image(
                              image: AssetImage(
                                  'assets/images/centre/toppieBg1.png'),
                              width: 70,
                              height: 70,
                            ),
                            Positioned(
                              child: Text(
                                dataList[3]['ratio'].toString() + '%',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFF2AB6F7),
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 10),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                                _showTime(
                                    dataList[3]['start'], dataList[3]['end']),
                                style: TextStyle(
                                    fontSize: 10,
                                    color: AppColors.textSecondary)),
                            Text(
                                "作业时间${dataList[3]['tappingTime'].toString()}h",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.textSecondary)),
                            Text("停机时间${dataList[3]['stopTime'].toString()}h",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.textSecondary))
                          ],
                        )
                      ],
                    ),
                  ),
              ],
            ),
        ]),
      ),
    );
  }
}
